package com.kw.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.kw.io.Resources;
import com.kw.pojo.Configuration;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * Created by Medivh on 2020/5/7.
 * 愿我出走半生,归来仍是少年
 * 解析confiig.xml
 */
public class XMlConfigBuilder {

    private Configuration configuration;

    public XMlConfigBuilder(){
        this.configuration = new Configuration();
    }

    public Configuration parseConfig(InputStream in) throws DocumentException {

            Document document = new SAXReader().read(in);
            Element rootElement =  document.getRootElement();
            List<Element> list  = rootElement.selectNodes("//property");
            Properties properties = new Properties();
            for(Element element:list){
                String name = element.attributeValue("name");
                String value = element.attributeValue("value");
                properties.setProperty(name,value);
            }

            DruidDataSource datasource = new DruidDataSource();
            datasource.setDriverClassName(properties.getProperty("driverClass"));
            datasource.setUrl(properties.getProperty("jdbcUrl"));
            datasource.setUsername(properties.getProperty("username"));
            datasource.setPassword(properties.getProperty("password"));
            this.configuration.setDataSource(datasource);
            XmlMapperBuilder mapperBuilder = new XmlMapperBuilder(configuration);
            List<Element> mapperList = rootElement.selectNodes("//mapper");
            for(Element element:mapperList){
                String mapperPath = element.attributeValue("resource");
                InputStream inputStream = Resources.getResourcesAsStream(mapperPath);
                mapperBuilder.parseMapper(inputStream);
            }



            return  configuration;

    }


    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }
}
